package middleware

import (
	"github.com/dgrijalva/jwt-go"
	"net/http"
	"strings"
	"time"
)

var jwtKey = []byte("your_secret_key")

type Claims struct {
	Username string `json:"username"`
	jwt.StandardClaims
}

func GenerateJWT(username string) (string, error) {
	expirationTime := time.Now().Add(2 * time.Hour)
	claims := &Claims{
		Username: username,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expirationTime.Unix(),
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err := token.SignedString(jwtKey)
	if err != nil {
		return "", err
	}

	return tokenString, nil
}

func MidAuth(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if Auth(w, r, "adminKey", "/dashboard/login.html") {
			next.ServeHTTP(w, r)
		}
	}
}

func Auth(w http.ResponseWriter, r *http.Request, keyName string, loginPath string) bool {
	//tokenString := r.Header.Get("Authorization")
	var tokenString string
	k := r.Cookies()
	for _, cookie := range k {
		if cookie.Name == keyName {
			tokenString = cookie.Value
		}
	}
	tokenString = strings.TrimPrefix(tokenString, "Bearer ")

	claims := &Claims{}
	token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
		return jwtKey, nil
	})

	if err == nil && token.Valid {
		return true
	}

	if loginPath == "" {
		http.Error(w, "Forbidden", http.StatusUnauthorized)
		//http.Error(w, "Forbidden", http.StatusForbidden)
	} else {
		http.Redirect(w, r, loginPath, http.StatusFound)
	}
	return false
}
